﻿using PBO.Util;
using PokemonBattle.BattleNetwork;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace PBO.Forms.NetworkForm.BattleForm.FourPlayer
{
    public partial class FourPlayerServerForm : Form
    {
        public FourPlayerServerForm()
        {
            InitializeComponent();
        }

        private string _myName;

        private List<BattleRule> _rules;
        private FourPlayerServer _server;

        public FourPlayerServerForm(string name, List<BattleRule> rules)
        {
            InitializeComponent();

            this.Icon = Properties.Resources.PokemonBall;
            _myName = name;
            _rules = rules;
            RunServer();
        }

        private void RunServer()
        {
            Player1Button.Text = _myName;

            _server = new FourPlayerServer(_myName);
            _server.OnPositionSet += SetPosition;
            if (_server.Initialize())
            {
                _server.RunThread();
            }
            else
            {
                ModShare.ShowInformation(this, "服务器初始化失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void SetPosition(byte position, string player)
        {
            SetButton(Controls.Find(string.Format("Player{0}Button", position), false)[0], player);
        }

        private void StartBattle()
        {
            Form form = ((MainForm)MdiParent).BuildBattleServerForm(_myName, BattleMode.Double_4P, _rules);
            form.Show();
        }

        private void SetButton(Control control, string txt)
        {
            if (InvokeRequired)
            {
                Invoke(new Action<Control, string>(SetButton), control, txt);
            }
            else
            {
                control.Text = txt;
                StartButton.Enabled = FullPlayer;
            }
        }

        private void StartButton_Click(object sender, EventArgs e)
        {
            StartBattle();
            _server.StartBattle();
            Thread.Sleep(500);
            Close();
        }

        private bool FullPlayer
        {
            get
            {
                if (Player2Button.Text.Length == 0)
                    return false;
                if (Player3Button.Text.Length == 0)
                    return false;
                if (Player4Button.Text.Length == 0)
                    return false;
                return true;
            }
        }

        private void FourPlayerServerForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_server != null)
            {
                _server.Stop();
                _server = null;
            }
        }

    }
}
